package com.bsoft.gol.hcs.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: map处理
 * @Author: zhaorb
 * @Date: 2020/10/15 13:50
 **/
public class MapUtil {

    private final static Logger logger = LoggerFactory.getLogger(MapUtil.class);

    /**
     * @Description: 对象转map
     * @Author: zhaorb
     * @Date: 2020/11/4 10:33
     **/
    public static Map<String, String> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }

        Map<String, String> map = new HashMap<String, String>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                Object object = field.get(obj);
                if (CommonUtils.isNotEmpty(object)) {
                    map.put(field.getName(), object.toString());
                } else {
                    map.put(field.getName(), "");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return map;
    }

    /**
     * @Description: 对象转map(key首字母大写)
     * @Author: zhaorb
     * @Date: 2020/11/4 10:33
     **/
    public static Map<String, String> objectToMapUpperCase(Object obj) {
        if (obj == null) {
            return null;
        }

        Map<String, String> map = new HashMap<String, String>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                Object object = field.get(obj);
                String name = field.getName();
                name = name.substring(0, 1).toUpperCase() + name.substring(1);
                if (CommonUtils.isNotEmpty(object)) {
                    map.put(name, object.toString());
                } else {
                    map.put(name, "");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return map;
    }
}